package com.egg.common.exception.config;

import com.egg.common.core.enums.ResponseCode;
import com.egg.common.core.exception.CustomException;
import com.egg.common.core.model.response.ResponseData;
import com.egg.common.translate.util.I18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author east
 */
@Slf4j
@Configuration
@RestControllerAdvice
public class ExceptionHandlerConfig implements ResponseBodyAdvice<Object> {


    /**
     * 全局异常拦截（拦截项目中的所有异常）
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Throwable.class})
    public <T> ResponseData<T> handlerException(Exception e) {
        ResponseData rd;
        if (e instanceof CustomException) {
            // 如果是自定义异常
            log.error("自定义异常", e);
            rd = ResponseData.error(((CustomException) e).getCode(), ((CustomException) e).getMessage());
        } else {
            // 未捕获异常
            log.error("=========================================未捕获全局异常开始================================================");
            log.error("未捕获全局异常信息", e);
            log.error("=========================================未捕获全局异常结束================================================");
            rd = ResponseData.error(ResponseCode.SYSTEM_ERROR.getCode(), ResponseCode.SYSTEM_ERROR.getMessage());
        }
        // 返回给前端
        return rd;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(
            Object body
            , MethodParameter methodParameter
            , MediaType mediaType
            , Class<? extends HttpMessageConverter<?>> aClass
            , ServerHttpRequest request
            , ServerHttpResponse response
    ) {
        if (body instanceof ResponseData) {
            ResponseData responseBody = (ResponseData) body;
            String translation = I18nUtil.translation(responseBody.getCode().toString(), responseBody.getMsg());
            responseBody.setMsg(translation);
            body = responseBody;
        }
        return body;
    }


}